import { useState, useEffect, useRef } from "react";
import { CommonModal } from "@/views/components/CommonModal";
import { CommonField } from "@/pages/OrderModule/common/components/CommonForm";
// import CommonInput from "@/pages/OrderModule/common/components/CommonInput";
import CommonImgsLoad from "@/components/CommonImgsLoad";
// import CommonInputNumber from "@/pages/OrderModule/common/components/CommonInputNumber";
import {
	Space,
	Col,
	Form,
	// Input
	Row,
	Radio,
	message,
	Tabs,
	Collapse,
	Button,
	Drawer,
	Tooltip
} from "antd";
import { PrefixPlaceholder, Input, PreInputNumber, CommonInput, CommonInputNumber } from "@/views/components/PrefixPlaceholder";
import IconFont from "@/components/IconFont";
import HelpInfo from "@/views/components/HelpInfo";
import { SPU_STATUS } from "@/views/utils/constant";
import AttrClassifyModal from "../Spu/ViewModal/AttrClassifyModal";
import { getGoodsAttribute, goodsSkuSubmit } from "../../../service";
import { cloneDeep } from "lodash";
import { skuCodePattern } from "@/views/utils/rules";
import Style from "./index.module.less";
import { useArchorList } from "./archorList";
import { useAnchor } from "@/pages/OrderModule/common/hooks/useAnchor";
import { DoubleLeftOutlined, ContainerTwoTone } from "@ant-design/icons";
import CommonDrawer from '@/components/CommonDrawer';
const ARCHOR_LIST_MAP = {
	basicInformation: 0, // 基础信息
	imageAttachment: 1, // 图片附件
	otherInformation: 2, // 其他信息
	otherSettings: 3 // 其他设置
};

//其他价格数量
const otherPrice = Array(5)
	.fill("")
	.map((_, index) => ({ label: `其他价格${index + 1}`, value: `price${index + 1}` }));
//其他属性数量
const otherAttr = Array(5)
	.fill("")
	.map((_, index) => ({ label: `其他属性${index + 1}`, value: `attribute${index + 1}` }));

const SpuViewModal = props => {
	const [form] = Form.useForm();
	// 商品详情数据
	const { details } = props;

	console.log("sku商品详情数据", details);

	const isEdit = !!details?.id;

	// 图片附件
	const goodsImage = details?.image;
	// 商品属性数据
	const [attrList, setAttrList] = useState([]);
	const [selectedRowKeys, setSelectedRowKeys] = useState([]);
	// 弹窗相关
	const [dialogName, setDialogName] = useState("");
	const [visible, setVisible] = useState(false);
	// 锚点
	const archorList = useArchorList();
	const [tab, setTab] = useState(archorList[ARCHOR_LIST_MAP.basicInformation].key);
	const contentWrapperRef = useRef(null);
	const anchorItems = useRef({});
	const { currentAnchor, scrollToAnchor } = useAnchor(contentWrapperRef, anchorItems);

	useEffect(() => {
		archorList.forEach(item => {
			anchorItems.current[item.key] = document.getElementById(item.key);
		});
	}, []);

	// 获取分类属性列表
	const getAttrList = async () => {
		const { data, success } = await getGoodsAttribute();
		if (success) {
			const attributesList = data.map(item => {
				if (item.type === 1)
					item.options = item.attributeValue.split(",").map(val => {
						return {
							label: val,
							value: val
						};
					});
				return item;
			});
			setAttrList([...attributesList]);
			form.setFieldsValue({
				// 判断是否编辑
				attributes:
					isEdit && details && Array.isArray(details.attributes)
						? details.attributes.map(e => e.attributeValue)
						: new Array(attributesList.length).fill()
			});
		}
	};

	//图片上传回调手动更新表单值
	const handleUploadImg = val => {
		console.log("上传图片路径", val);
		form.setFieldsValue({
			image: val
		});
	};
	// 创建
	function handleOk() {
		form
			.validateFields()
			.then(val => {
				const API_DATA = form.getFieldsValue();
				console.log("API_DATA", API_DATA);
				if (isEdit) API_DATA.id = details.id;
				goodsSkuSubmit(API_DATA).then(res => {
					if (res.success) {
						message.success("创建成功");
						props.onCancel();
						props.fetchList();
					}
				});
			})
			.catch(err => {
				console.log("err", err);
			});
	}

	useEffect(() => {
		getAttrList();
	}, []);

	return (
		<CommonDrawer
			title="编辑商品"
			open={true}
			width="80%"
			onClose={props.onCancel}
			footer={
				<Row justify="end">
					<Col>
						<Space>
							<Button size="middle" onClick={props.onCancel}>
								取消
							</Button>
							<Button size="middle" type="primary" onClick={handleOk}>
								保存
							</Button>
						</Space>
					</Col>
				</Row>
			}
		>
			<div className="flex" style={{ flexDirection: "column", height: "100%" }}>
				<div className={Style.archor_tab + " rule-reset"}>
					<Tabs
						activeKey={tab}
						onChange={val => {
							setTab(val);
							scrollToAnchor(val);
						}}
					>
						{archorList.map(item => (
							<Tabs.TabPane tab={item.title} key={item.key}></Tabs.TabPane>
						))}
					</Tabs>
				</div>
				<div className={Style.detail_inner} ref={contentWrapperRef}>
					<Form form={form} initialValues={{ ...details, goodsImage, attributes: [] } || {}}>
						<Collapse
							defaultActiveKey={Object.keys(ARCHOR_LIST_MAP)}
							ghost
							expandIcon={({ isActive }) => (
								<DoubleLeftOutlined rotate={isActive ? 270 : 90} style={{ fontSize: "16px", color: "#4E5969" }} />
							)}
							expandIconPosition="end"
							className={Style["reset-collapse"]}
						>
							<Collapse.Panel header={archorList[ARCHOR_LIST_MAP.basicInformation].render()} key="basicInformation">
								<Row gutter={[12, 6]} className={Style.container}>
									<Form.Item
										name="skuName"
										style={{ width: "calc(38% + 10px)" }}
										rules={[{ required: true, message: "请输入商品名称" }]}
									>
										<CommonInput placeholder="请输入商品名称" aria-required maxLength={100} showCount={true} />
									</Form.Item>
									<Row className={Style.item}>
										<Col span={22}>
											<Form.Item name="skuCode">
												<CommonInput placeholder="请输入商品编码" disabled aria-required showCount maxLength={200} />
											</Form.Item>
										</Col>
										<Col span={1} offset={1}>
											<Tooltip
												placement="bottomLeft"
												title={
													"商品编码是商品的唯一标识，与平台的商家编码/商品编码对应；请不要使用除-_/以外的符号如需打印条形码请不要超过17位"
												}
											>
												<IconFont type="iconwenhao" />
											</Tooltip>
										</Col>
									</Row>
									<Row className={Style.item}>
										<Col span={22}>
											<Form.Item name="spuCode">
												<CommonField
													Component={Input}
													props={{
														placeholder: "请输入款式编码",
														showCount: true,
														maxLength: 64
													}}
												/>
											</Form.Item>
										</Col>
										<Col span={1} offset={1}>
											<Tooltip
												placement="bottomLeft"
												color="#000000"
												title={
													"不同商品编码可维护相同款式编码表示属同款；修改款式编码后，如原款式编码下没有其它商品，则原款式编码资料被删除"
												}
											>
												<IconFont type="iconwenhao" />
											</Tooltip>
										</Col>
									</Row>
									{/* <Form.Item name="colorSpecifications" className={Style.item}>
										<CommonField
											Component={Input}
											props={{
												placeholder: "颜色尺码",
                        showCount: true,
												maxLength: 100
											}}
										/>
									</Form.Item> */}
									<Form.Item alt="占位用的" name="color" className={Style.item}></Form.Item>
									<Form.Item name="colour" className={Style.item}>
										<CommonField
											Component={Input}
											props={{
												placeholder: "颜色",
												showCount: true,
												maxLength: 100
											}}
										/>
									</Form.Item>
									<Form.Item name="specs" className={Style.item}>
										<CommonField
											Component={Input}
											props={{
												placeholder: "尺码",
												showCount: true,
												maxLength: 100
											}}
										/>
									</Form.Item>
									<Form.Item name="skuAbbreviation" className={Style.item}>
										<CommonField
											Component={Input}
											props={{
												placeholder: "商品简称",
												maxLength: 40,
												showCount: true
											}}
										/>
									</Form.Item>
									<Form.Item name="retailPrice" className={Style.item}>
										<CommonInputNumber min={0} placeholder="请输入零售价" precision={2} controls={false} />
									</Form.Item>
									<Form.Item name="costPrice" rules={[{ required: true, message: "请输入成本价" }]} className={Style.item}>
										<CommonInputNumber min={0} placeholder="请输入成本价" aria-required precision={2} controls={false} />
									</Form.Item>
									<Form.Item name="purchasePrice" className={Style.item}>
										<CommonInputNumber min={0} precision={2} placeholder="采购价" disabled controls={false} />
									</Form.Item>
									<Form.Item name="weight" className={Style.item}>
										<CommonInputNumber
											placeholder="重量"
											min={0}
											precision={2}
											controls={false}
											addonAfter={<span class="tips">kg</span>}
											style={{ width: "100%" }}
										/>
									</Form.Item>
								</Row>
							</Collapse.Panel>
							<Collapse.Panel header={archorList[ARCHOR_LIST_MAP.imageAttachment].render()} key="imageAttachment">
								<Row gutter={[12, 6]}>
									<Col span={24}>
										<Form.Item valuePropName="fileList" name="image">
											<CommonImgsLoad size={1} img={goodsImage} antPreview={true} handleOk={handleUploadImg} upLoadText="请上传" />
										</Form.Item>
									</Col>
								</Row>
							</Collapse.Panel>
							<Collapse.Panel
								header={archorList[ARCHOR_LIST_MAP.otherInformation].render()}
								key="otherInformation"
								// style={{ position: "relative" }}
							>
								{/* <Button
								type="text"
								onClick={() => setDialogName("AttrClassifyModal")}
								style={{ position: "absolute", right: 0, top: "12px" }}
							>
								<ContainerTwoTone style={{ marginRight: 5 }} />
								维护分类属性
							</Button> */}
								<Row gutter={[12, 6]} className={Style.container}>
									{otherPrice.map(item => (
										<Form.Item key={item.value} name={item.value} className={Style.item}>
											<CommonInputNumber min={0} placeholder={item.label} precision={2} controls={false} />
										</Form.Item>
									))}
									{otherAttr.map(item => (
										<Form.Item key={item.value} name={item.value} className={Style.item}>
											<CommonField
												Component={Input}
												props={{
													placeholder: item.label,
													maxLength: 50,
													showCount: true
												}}
											/>
										</Form.Item>
									))}
									<Form.Item name="productIngredients" className={Style.item}>
										<CommonInput placeholder="商品成分" showCount maxLength={50} />
									</Form.Item>
									<Form.Item name="customAttribute" className={Style.item}>
										<CommonInput placeholder="自定义属性" showCount maxLength={50} />
									</Form.Item>
								</Row>
							</Collapse.Panel>
							{/* <Collapse.Panel header={archorList[ARCHOR_LIST_MAP.otherSettings].render()} key="otherSettings">
								<Row gutter={[12, 6]}>
									<Col span={24}>
										<Form.Item label="商品状态" name="status" initialValue={0}>
											<Radio.Group>
												{SPU_STATUS.map(item => (
													<Radio key={item.value} value={item.value}>
														{item.label}
													</Radio>
												))}
											</Radio.Group>
										</Form.Item>
									</Col>
								</Row>
							</Collapse.Panel> */}
						</Collapse>
					</Form>
					{dialogName === "AttrClassifyModal" && (
						<AttrClassifyModal
							attrList={attrList}
							setVisible={setVisible}
							getAttrList={getAttrList}
							onCancel={() => {
								setDialogName("");
							}}
						/>
					)}
				</div>
			</div>
		</CommonDrawer>
	);
};
export default SpuViewModal;
